package com.ygo.feihua.fragment;


import android.graphics.*;
import android.os.*;
import android.support.v4.app.*;
import android.view.*;
import android.widget.*;
import cn.bmob.v3.*;
import com.ygo.feihua.BmobTable.*;
import java.io.*;
import java.util.*;
import cn.bmob.v3.datatype.*;
import java.text.*;
import cn.bmob.v3.listener.*;
import javax.security.auth.*;
import android.content.*;
import android.view.View.*;
import cn.bmob.v3.exception.BmobException;
import com.ygo.feihua.Management.ShequManagement;
import android.widget.AdapterView.OnItemClickListener;
import android.support.v4.util.*;
import android.support.v4.widget.*;
import com.ygo.feihua.adapter.*;
import android.widget.AdapterView.*;
import com.msk86.ygoroid.newutils.*;
import android.support.transition.*;
import android.transition.ChangeImageTransform;
import com.ygo.feihua.util.*;
import com.ygo.feihua.console.*;
import com.ygo.feihua.task.*;
import android.support.v7.widget.*;
import android.util.*;
import com.ygo.feihua.*;
import com.ygo.feihua.R;

public class FragmentShequ extends Fragment implements SwipeRefreshLayout.OnRefreshListener,Task
{

	private static final int INIT_SHEQU_ADAPTER = 0;

	private boolean isInitShequ = false;

	private int skipPageNum=1;

	@Override
	public void execute(int number)
	{
		han.sendEmptyMessage(number);
		// TODO: Implement this method
	}
	
	Handler han=new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			// TODO: Implement this method
			super.handleMessage(msg);
			switch(msg.what){
				case INIT_SHEQU_ADAPTER:
					
					
					sq_rec.setLayoutManager(new LinearLayoutManager(getActivity()));
					adapter = new ShequAdapter(getActivity(), sqm.getData());
					sq_rec.setAdapter(adapter);
					sq_rec.setItemAnimator(new DefaultItemAnimator());
					
					sq_rec.addOnScrollListener(new RecyclerView.OnScrollListener() {
												   @Override
												   public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
													   LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
													   int totalItemCount = recyclerView.getAdapter().getItemCount();
													   int lastVisibleItemPosition = lm.findLastVisibleItemPosition();
													   int visibleItemCount = recyclerView.getChildCount();

													   if (newState == RecyclerView.SCROLL_STATE_IDLE
														   && lastVisibleItemPosition == totalItemCount - 1
														   && visibleItemCount > 0) {
														   //加载更多
														   
														   onLoad();
													   }
												   }
												   
											   });
					
					
					sq_sw.setColorSchemeResources(R.color.colorMain);
					sq_sw.setOnRefreshListener(FragmentShequ.this);
					//手动调用,通知系统去测量
					sq_sw.measure(0,0);

					sqm=ShequManagement.getdx();

					sq_sw.setRefreshing(true);
					onRefresh();
					
					break;
			}
		}
		
	};

	private RecyclerView sq_rec;
	private ShequAdapter adapter;
	private SwipeRefreshLayout sq_sw;
	
	private Context context;
	private Gongju gj;
	private DialogUtils du;
	private ShequManagement sqm;
	private TaskConsole tac;
	private TieType tie_type=null;

	public  void longTieType()
	{
		tie_type=null;
		onRefresh();
		// TODO: Implement this method
	}

	public TieType getShequType(){
		return tie_type;
	}
	
	
	public void tie_type(final String title,final TieType tt)
	{
		du.dialogj1(false,"","加载中,请稍等");
		BmobQuery<TieType> bq=new BmobQuery<TieType>();
		
		if(tt==null){
			bq.addWhereDoesNotExists("type");
		}else{
		bq.addWhereEqualTo("type",tt);
		}
		bq.order("-createdAt");
		bq.findObjects(new FindListener<TieType>(){

				@Override
				public void done(final List<TieType> ltt, BmobException p2)
				{
					if(p2==null){
						if(ltt.size()!=0){
					ListView ll=du.dialogl1(true,title,new TieTypeAdapter(getActivity(),ltt));
					ll.setOnItemClickListener(new OnItemClickListener(){

							@Override
							public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
							{
								tie_type(ltt.get(p3).getName(),ltt.get(p3));
								
								// TODO: Implement this method
							}
						});
						}else{
							((CeHua)getActivity()).setSettingImage(tt.getIcon().getFileUrl());
							du.dis();
							tie_type=tt;
							onRefresh();
							
						}
					}else{
						du.dis();
						gj.toastBmobException(sq_rec,"加载失败",p2);
					}
					// TODO: Implement this method
				}
			});
		// TODO: Implement this method
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		
		View view=inflater.inflate(R.layout.fragment_shequ,container,false);	
		
		sq_rec = (RecyclerView) view.findViewById(R.id.sq_rec);
		sq_sw=(SwipeRefreshLayout) view.findViewById(R.id.sq_sw);
		
		tac=TaskConsole.getDx();	
		context=getActivity();
		sqm=ShequManagement.getdx();
		gj=Gongju.getdx(context);
		du=DialogUtils.getdx(context);
		
		// TODO: Implement this method
		return view;
	}

	@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) { //相当于Fragment的onResume
            //在这里去请求数据。。。
			if(!isInitShequ){
				isInitShequ=true;
			tac.addTask(FragmentShequ.this,INIT_SHEQU_ADAPTER);
			}
        } else { //相当于Fragment的onPause

        }
    }
	
	@Override
	public void onRefresh()
	{
		BmobQuery<Tiezi> tie=new BmobQuery<Tiezi>();
		tie.setLimit(20);
		tie.order("-createdAt");
		if(tie_type!=null){
		tie.addWhereEqualTo("tie_type",tie_type);
		}
		tie.include("tiezuo");// 希望在查询帖子信息的同时也把发布人的信息查询出来
		tie.findObjects(new FindListener<Tiezi>(){

				@Override
				public void done(List<Tiezi> p1, BmobException p2)
				{
					if(p2==null){
						sqm.setData(p1);
						if(p1.size()!=0){
						sqm.setUpdatedata(p1.get(p1.size()-1).getUpdatedAt());
						}
						adapter.notifyDataSetChanged();
						skipPageNum=1;
					}else{
						gj.toastBmobException(sq_sw,"刷新失败",p2);//.show("刷新失败,原因为"+p2);
					}
					sq_sw.setRefreshing(false);
					// TODO: Implement this method
				}
			});
		
	
	}

	public void onLoad() {
		BmobQuery<Tiezi> tie=new BmobQuery<Tiezi>();
		tie.setLimit(20);
		tie.setSkip(20*skipPageNum);
		tie.order("-createdAt");
		if(tie_type!=null){
			tie.addWhereEqualTo("tie_type",tie_type);
		}
		tie.include("tiezuo");// 希望在查询帖子信息的同时也把发布人的信息查询出来
		tie.findObjects(new FindListener<Tiezi>(){

				@Override
				public void done(List<Tiezi> p1, BmobException p2) {
					if (p2 == null) {
						if (p1.size() == 0) {
							gj.show("没有数据了喵~");
						} else {
							for (final Tiezi tt:p1) {				
								sqm.addData(tt);
							}
							sqm.setUpdatedata(p1.get(p1.size() - 1).getUpdatedAt());
							adapter.sx();
							skipPageNum++;
							// TODO: Implement this method
						}
					} else {
						gj.toastBmobException(sq_rec, "加载数据失败", p2);
					}
					// TODO: Implement this method
				}
			});
	}
}
